package com.lijinjiang.util;

import java.io.*;
import java.util.Properties;

/**
 * @ClassName FileUtil
 * @Description 文件工具类
 * @Author Li
 * @Date 2022/8/15 12:48
 * @ModifyDate 2022/8/15 12:48
 * @Version 1.0
 */
public class FileUtil {

    // 存放数据库连接配置文件的目录
    public final static String SC_PATH = "profile" + File.separator;

    public final static String HOST = "host";
    public final static String PORT = "port";
    public final static String USER = "user";
    public final static String PASSWORD = "password";

    /**
     * 创建一个新文件的工具方法
     */
    public static void createProfile(File file) {
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            throw new RuntimeException("写入文件错误:" + e.getMessage());
        }
    }

    /**
     * 将属性文件保存到参数的文件中，并添加对应的注释
     * @param connProfile
     * @param prop
     * @param comment
     */
    public static void saveProperties(File connProfile, Properties prop, String comment) {
        try {
            // 写入properties文件中
            FileOutputStream fos = new FileOutputStream(connProfile);
            prop.store(fos, comment);
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException("配置文件写入本地错误！");
        }
    }

    /**
     * 根据properties文件获取Properties对象
     * @param profile
     * @return
     */
    public static Properties getProperties(File profile) throws IOException {
        Properties prop = new Properties();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(profile));
        prop.load(bis);
        bis.close();
        return prop;
    }

    /**
     * 获取不带后缀文件名
     * @param profile
     * @return
     */
    public static String getFileName(File profile) {
        String fileName = profile.getName();
        if (fileName.lastIndexOf(".") != -1) {
            return fileName.substring(0, fileName.lastIndexOf("."));
        }
        return fileName;
    }
}
